#!/bin/bash

# OpenCloudOS 专用安装脚本
# 适用于腾讯云 OpenCloudOS 系统

set -e

# 配置变量
PROJECT_NAME="tetris-game"
PROJECT_DIR="/opt/jpom/projects/${PROJECT_NAME}"
WEBHOOK_PORT="9999"
APP_PORT="3000"
GIT_REPO="https://gitee.com/cailei/tetris-game.git"  # 请替换为您的仓库地址

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
    exit 1
}

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    error "请使用 root 用户运行此脚本"
fi

log "🚀 开始配置 OpenCloudOS 服务器环境..."

# 1. 检查系统版本
log "📋 检查系统信息..."
if [ -f /etc/os-release ]; then
    . /etc/os-release
    log "系统: $NAME $VERSION"
else
    log "系统: OpenCloudOS (未知版本)"
fi

# 2. 清理可能有问题的仓库
log "🧹 清理仓库配置..."
if [ -f /etc/yum.repos.d/docker-ce.repo ]; then
    rm -f /etc/yum.repos.d/docker-ce.repo
    log "已删除旧的 Docker 仓库配置"
fi

# 3. 更新系统
log "📦 更新系统包..."
dnf update -y

# 4. 安装 EPEL 仓库
log "📦 安装 EPEL 仓库..."
dnf install -y epel-release

# 5. 安装基础软件
log "🔧 安装基础软件..."
dnf install -y \
    curl \
    wget \
    git \
    python3 \
    python3-pip \
    nginx \
    firewalld \
    net-tools \
    vim \
    htop \
    tar \
    gzip

# 6. 安装 Docker (使用系统仓库)
log "🐳 安装 Docker..."
if ! command -v docker &> /dev/null; then
    # 尝试从系统仓库安装
    dnf install -y docker || {
        log "系统仓库安装失败，尝试手动安装..."
        # 手动安装 Docker
        curl -fsSL https://get.docker.com -o get-docker.sh
        sh get-docker.sh
        rm -f get-docker.sh
    }
else
    log "Docker 已安装，跳过..."
fi

# 7. 启动 Docker 服务
log "🐳 配置 Docker 服务..."
systemctl start docker
systemctl enable docker
usermod -aG docker $USER

# 8. 安装 Docker Compose
log "🐳 安装 Docker Compose..."
if ! command -v docker-compose &> /dev/null; then
    # 使用 pip 安装 docker-compose
    pip3 install docker-compose || {
        # 如果 pip 安装失败，使用二进制文件
        log "使用二进制文件安装 Docker Compose..."
        DOCKER_COMPOSE_VERSION="2.20.0"
        curl -L "https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
        ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
    }
fi

# 9. 安装 Python 依赖
log "🐍 安装 Python 依赖..."
pip3 install flask

# 10. 创建项目目录
log "📁 创建项目目录..."
mkdir -p "${PROJECT_DIR}"
mkdir -p /var/log

# 11. 克隆项目代码
log "📥 克隆项目代码..."
cd "${PROJECT_DIR}"
if [ -d ".git" ]; then
    log "更新现有仓库..."
    git pull origin main || git pull origin master
else
    log "克隆新仓库..."
    git clone "${GIT_REPO}" . || {
        warn "Git 克隆失败，请手动克隆项目到 ${PROJECT_DIR}"
        log "手动克隆命令: git clone ${GIT_REPO} ${PROJECT_DIR}"
    }
fi

# 12. 配置权限
log "🔐 配置文件权限..."
if [ -f jpom-build.sh ]; then
    chmod +x jpom-build.sh
fi
if [ -f webhook-receiver.py ]; then
    chmod +x webhook-receiver.py
fi
if [ -f server-setup.sh ]; then
    chmod +x server-setup.sh
fi

# 13. 配置防火墙
log "🔥 配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-port=${WEBHOOK_PORT}/tcp
firewall-cmd --permanent --add-port=${APP_PORT}/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 14. 配置 Nginx
log "🌐 配置 Nginx..."
systemctl start nginx
systemctl enable nginx

# 备份原配置
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

# 创建项目配置
cat > /etc/nginx/conf.d/tetris-webhook.conf << 'EOF'
server {
    listen 80;
    server_name _;
    
    # 增加客户端最大请求体大小
    client_max_body_size 10M;
    
    # Webhook 接收器
    location /webhook/ {
        proxy_pass http://127.0.0.1:9999;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # 游戏应用
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:9999/health;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        access_log off;
    }
    
    # 静态文件缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# 测试 Nginx 配置
nginx -t && systemctl reload nginx

# 15. 配置 Webhook 服务
log "⚙️ 配置 Webhook 服务..."
if [ -f webhook-receiver.service ]; then
    cp webhook-receiver.service /etc/systemd/system/
    systemctl daemon-reload
    systemctl enable webhook-receiver
    systemctl start webhook-receiver
else
    warn "webhook-receiver.service 文件不存在，请手动配置"
fi

# 16. 配置 SELinux (如果启用)
log "🔒 配置 SELinux..."
if command -v getenforce >/dev/null 2>&1; then
    if [ "$(getenforce)" = "Enforcing" ]; then
        log "配置 SELinux 策略..."
        setsebool -P httpd_can_network_connect 1
        setsebool -P httpd_can_network_relay 1
    fi
fi

# 17. 等待服务启动
log "⏳ 等待服务启动..."
sleep 5

# 18. 检查服务状态
log "📊 检查服务状态..."
echo ""
echo "=== 服务状态检查 ==="
systemctl is-active docker && echo "✅ Docker: 运行中" || echo "❌ Docker: 未运行"
systemctl is-active nginx && echo "✅ Nginx: 运行中" || echo "❌ Nginx: 未运行"
systemctl is-active webhook-receiver && echo "✅ Webhook: 运行中" || echo "❌ Webhook: 未运行 (需要项目文件)"
systemctl is-active firewalld && echo "✅ 防火墙: 运行中" || echo "❌ 防火墙: 未运行"

# 19. 测试 Docker
log "🧪 测试 Docker..."
docker --version
docker run --rm hello-world && log "Docker 测试成功" || warn "Docker 测试失败"

# 20. 显示配置信息
echo ""
log "✅ OpenCloudOS 服务器配置完成！"
echo ""
echo "📋 配置信息:"
echo "  服务器IP: 82.157.51.127"
echo "  项目目录: ${PROJECT_DIR}"
echo "  Webhook端口: ${WEBHOOK_PORT}"
echo "  应用端口: ${APP_PORT}"
echo ""
echo "🌐 访问地址:"
echo "  游戏应用: http://82.157.51.127"
echo "  健康检查: http://82.157.51.127/health"
echo "  Webhook URL: http://82.157.51.127/webhook/gitee"
echo ""
echo "🔧 下一步操作:"
echo "1. 确保项目代码已克隆到: ${PROJECT_DIR}"
echo "2. 在 Gitee 仓库中配置 Webhook: http://82.157.51.127/webhook/gitee"
echo "3. 推送代码测试自动部署"
echo "4. 手动构建测试: cd ${PROJECT_DIR} && ./jpom-build.sh"
echo ""
echo "📝 查看日志:"
echo "  Webhook 日志: tail -f /var/log/webhook-receiver.log"
echo "  Nginx 日志: tail -f /var/log/nginx/error.log"
echo "  Docker 日志: docker logs tetris-game"
echo ""
echo "🎉 环境配置完成！准备享受自动化部署吧！"
